package kotlinx.coroutines.script.tes

import sample.ui.DescLayout
import abc.reflect.AESUtils
import kotlinx.coroutines.Dispatchers
import v9.assist.script.sSceneCompletedTime
import java.io.File
import java.util.*

object DiskLogUtils {
//    private var recordTimes = 0L
    private val lock = Any()
    private val dir get() = FileUtils.cacheDir("log")
    private val logList = LinkedList<String>()
    val logText: File get() {
        val out = File(dir, "log.txt")
        if (!out.exists()) out.createNewFile()
        return out
    }

    fun record(output: String) {
        appScopeLaunch(Dispatchers.IO) {
            synchronized(lock) {
                logList.add("${System.currentTimeMillis().toTime("yyyy-MM-dd HH:mm:ss.SSS")} $output")
                if (logList.size > 400) logList.removeAt(0) // 不需要记录这个了
            }
        }
    }

    fun saveToDisk() {
        appScopeLaunch(Dispatchers.IO) {
            val output = StringBuilder()
            synchronized(lock) {
                if (sSceneCompletedTime > 0) {
                    logList.add("${System.currentTimeMillis().toTime("yyyy-MM-dd HH:mm:ss.SSS")} 完成次数 $sSceneCompletedTime")
                }
                logList.add("${System.currentTimeMillis().toTime("yyyy-MM-dd HH:mm:ss.SSS")} 运行时长${DescLayout.runTime}s $appVersionInfo ${phoneDefaultDisplayPoint.x}x${phoneDefaultDisplayPoint.y} dpi${phoneDensityDpi}")
                logList.forEach {
                    output.append(it).append("\n")
                }
            }
            val encrypted = AESUtils.encrypt(AESUtils.K, output.toString())
            try { logText.delete() } catch (ignore: Throwable) { }
            FileUtils.write(logText, encrypted)
        }
    }


}